import asyncio
import json
import re
from sqlalchemy.orm import Session

from app.web.chatbot.FlowChatBot import FlowChatBot
from app.web.crontab.BaseTask import BaseTask
from app.web.models.BaseModel import ReportStatus
from app.web.models.Database import engine
from app.web.models.JobSeeker import Resume
from app.web.models.Recruiter import JobPost, ResumeReport, JobPostResume

from app.logger import logger


class ResumeAnalysisTask(BaseTask):

    __name = "Resume Analysis"
    __pattern = r'{\s*"match_rate"\s*:\s*\d+(?:\.\d+)?\s*,\s*"description"\s*:\s*"[^"\\]*(?:\\.[^"\\]*)*"\s*}'

    def run(self):
        asyncio.run(self._run())

    async def _run(self):
        with Session(engine) as session:
            q = session.query(ResumeReport).filter(ResumeReport.status == ReportStatus.RUNNING)
            has_running = session.query(q.exists()).scalar()
            logger.info(f"Run Task[{self.__name}], has running task: {has_running}")
            if has_running:
                return
            resume_report: ResumeReport = session.query(ResumeReport).order_by(ResumeReport.created_at)\
                .filter(ResumeReport.status == ReportStatus.UNEXECUTED).first()
            if resume_report is None:
                return
            job_post_resume: JobPostResume = session.query(JobPostResume).get(resume_report.job_post_resume)
            job_post: JobPost = session.query(JobPost).get(job_post_resume.job_post)
            resume: Resume = session.query(Resume).get(job_post_resume.resume)
            if resume is not None and job_post is not None:
                resume_report.status = ReportStatus.RUNNING
                session.commit()
                prompt = f"""
                我是一名招聘专员，我需要通过简历文件({resume.file_path})与我的招聘岗位{job_post.title}进行分析，并得到简历和岗位之间的匹配度（值需要在0至1之间，越接近1代表越匹配）;
                重点的要求如下:
                {job_post.requirements}
                详细的要求如下：
                {job_post.description}
                """
                logger.info(f"Ask {prompt}")
                chat_bot = FlowChatBot()
                result = await chat_bot.ask(prompt)
                match = re.search(self.__pattern, result, re.DOTALL)
                if match:
                    json_str = match.group()
                    logger.info(f"JSON Str: {json_str}")
                    result_dict = json.loads(json_str)
                    resume_report.match_rate = result_dict["match_rate"]
                    resume_report.description = result_dict["description"]
                    resume_report.status = ReportStatus.COMPLETED
                    session.commit()
                else:
                    resume_report.description = result
                    resume_report.status = ReportStatus.COMPLETED
                    session.commit()

    def get_settings(self) -> dict:
        return {'minutes': 2}

    def get_trigger(self) -> str:
        return 'interval'
